package com.mk.legoscans2.data;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;

import com.mk.legoscans2.Message;

public class MessageService extends SaxFeedParser {

	private String _domain;
	private int _port;

	public MessageService(String domain, int port){
		_domain = domain;
		_port = port;
	}
	
	public List<Message> getNewMessages(int lastMessageId) {
		URL url;
		try {
			url = new URL("http://" + _domain + ":" + _port + "/message/GetNewMessages/xml/" + lastMessageId + "?source=test");
		} catch (MalformedURLException ex) {
			throw new RuntimeException(ex);
		}
		
		final List<Message> messages = new ArrayList<Message>();
		final Message m = new Message();
		
		RootElement root = new RootElement("Messages");
		Element item = root.getChild("Message");
		
		item.setEndElementListener(new EndElementListener() {
			public void end() {
				messages.add(m.clone());
				m.reset();
			}
		});
		
		item.getChild("Id").setEndTextElementListener(new EndTextElementListener() {
			public void end(String body) {
				m._id = Integer.parseInt(body);
			}
		});
		
		item.getChild("Msg").setEndTextElementListener(new EndTextElementListener() {
			public void end(String body) {
				m._msg = body;
			}
		});
		
		item.getChild("MessageType").setEndTextElementListener(new EndTextElementListener() {
			public void end(String body) {
				m._type = body;
			}
		});
		
		item.getChild("TimeStamp").setEndTextElementListener(new EndTextElementListener() {
			public void end(String body) {
				SimpleDateFormat f = new SimpleDateFormat("y-M-d H:m:s");//2012-02-10T14:20:00
				try {
					m._timeStamp = f.parse(body.replace("T", " "));
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
		});
		
		if(!ExecuteParser(url, root))
			return null;
		
		return messages;
	}

}
